package com.dhecp.project.system.service.impl;

import java.util.*;

import com.alibaba.fastjson.JSON;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.utils.StringUtils;
import com.dhecp.common.utils.TypeUtils;
import com.dhecp.core.constant.DataFiltering;
import com.dhecp.core.utils.PageUtils;
import com.dhecp.framework.util.ShiroUtils;
import com.dhecp.project.system.domain.*;
import com.dhecp.project.system.mapper.SysDictionaryForFieldMapper;
import com.dhecp.project.system.mapper.SysDictionaryForModuleMapper;
import com.dhecp.project.system.service.SysDictionaryForFieldService;
import com.dhecp.project.system.service.SysDictionaryRelationForModuleService;
import com.dhecp.project.system.service.SysSettingService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 字段数据字典、属性、查询条件、数据权限
 * @author DH-Xxj
 * @version 2019年8月28日
 */
@Service
public class SysDictionaryForFieldServiceImpl implements SysDictionaryForFieldService {

	@Autowired
	private SysDictionaryForFieldMapper dictionaryForFieldMapper;

	@Autowired
	private SysDictionaryForModuleMapper dictionaryForModuleMapper;
	
	@Autowired
    private SysDictionaryRelationForModuleService dictionaryRelationForModuleService;

	@Autowired
	private SysSettingService settingService;
	
	/**
	 * 查询所有功能字段数据字典列表
	 * @param params
	 * @return List-DictionaryForField
	 * @author lwl
	 * @throws Exception 
	 */
	@Override
	public List<SysDictionaryForField> queryDictionaryForField(Map<String, Object> params) throws Exception {
		params.put(DataFiltering.DATA_WHERE,getWhereStr(params));
		PageUtils.startPage();
		return dictionaryForFieldMapper.findDictionaryForField(params);
	}

	/**
	 * 根据功能表名查询字段数据字典列表
	 * @param params
	 * @return List-DictionaryForField
	 * @author lwl
	 * @throws Exception 
	 */
	@Override
	public List<SysDictionaryForField> queryDictionaryForFieldByTableName(Map<String, Object> params) throws Exception{
		String oldModuleTable="";
		if(params.get("moduleTable")!=null)oldModuleTable=params.get("moduleTable").toString();
		params.put("trueTable",true);
		params.put(DataFiltering.DATA_WHERE,getWhereStr(params));
		params.put("moduleTable",oldModuleTable);
		PageUtils.startPage();
		return dictionaryForFieldMapper.findDictionaryForFieldByTableName(params);
	}
	
	/**
	 * 根据guid查询字段数据字典列表
	 * @param params
	 * @return 实体SysDictionaryForField
	 * @author lwl
	 */
	@Override
	public SysDictionaryForField queryDictionaryForFieldByGuid(String guid) {
		return dictionaryForFieldMapper.findDictionaryForFieldByGuid(guid);
	}

	/**
	 * 获取导入模板、导出数据 字段列表(以List形式返回)
	 * @param moduleTable 必要参数：功能唯一标识
     * @param entity 必要参数：用于获取实体属性名取代对应字典字段名，解决大小写敏感问题
	 * @param getFieldAttributesType 可选参数：查询范围（export：导出字段，template：导入模板字段，templateedit：可编辑导入模板字段）
	 * @param getFieldAttributesSystemType 可选参数：类型【web：网页端；mobile：手机端】
	 * @param specifiedExportFields 可选参数：指定要导出的字段，示例：Field1,Field2,Field3
	 * @return List-SysDictionaryForExport
	 * @author DH-Xxj
	 */
	@Override
	public List<SysDictionaryForExport> queryExportFieldList(Map<String, Object> params) {
    	params.put("loginUser", ShiroUtils.getMandatorId()); //当前用户
    	if (params.get("getFieldAttributesType") == null || params.get("getFieldAttributesType") == "" || !"template".equals(params.get("getFieldAttributesType").toString())){
        	params.put("getFieldAttributesType", "export"); //export：导出字段，template：导入模板字段
    	}
    	if (params.get("getFieldAttributesSystemType") == null || params.get("getFieldAttributesSystemType") == ""){
        	params.put("getFieldAttributesSystemType", "web"); //web：网页端；mobile：手机端
    	}
    	
    	String specifiedExportFields = "";
    	if (params.get("specifiedExportFields") != null && params.get("specifiedExportFields") != ""){
    		specifiedExportFields = params.get("specifiedExportFields").toString();
    	}
    	String [] specifiedExportFieldList = specifiedExportFields.split(","); 
    	
    	List<SysDictionaryForExport> exportFieldList = dictionaryForFieldMapper.findExportField(params);
    	List<SysDictionaryForExport> exportFieldListR = new ArrayList<SysDictionaryForExport>();
		if (params.get("entity") != null && params.get("entity") != ""){
			Map<String, Object> entityFieldMap = TypeUtils.entityFieldsToMap(params.get("entity"));
			for (SysDictionaryForExport exportField : exportFieldList){
                if (entityFieldMap.get(exportField.getFields().toLowerCase()) != null && !"".equals(entityFieldMap.get(exportField.getFields().toLowerCase()))){
                	exportField.setFields(entityFieldMap.get(exportField.getFields().toLowerCase()).toString());
                }
				if ("".equals(specifiedExportFields) || Arrays.asList(specifiedExportFieldList).contains(exportField.getFields().toLowerCase())){
					exportFieldListR.add(exportField);
				}
			}
		}
    	return exportFieldListR;
	}
		
	/**
	 * 获取功能页面中字段及各属性(以List形式返回)
	 * @param moduleTable 必要参数：功能唯一标识
     * @param entity 必要参数：用于获取实体属性名取代对应字典字段名，解决大小写敏感问题
	 * @param matchUserDefined 可选参数：是否使用用户自定义字段属性（1：结果受用户自定义字段属性影响[默认]，0：结果忽略用户自定义字段属性）
	 * @param getFieldAttributesType 可选参数：查询范围（page：全部字段[默认]，pagecallin：调入页网格，pageinhead：头部字段，pageinbottom：底部字段，pagenotingrid：非网格字段，pageingrid：网格字段，pagestatic：静态字段）
	 * @param getFieldAttributesSystemType 可选参数：类型【web：网页端；mobile：手机端】
	 * @return List-DictionaryForField
	 * @author DH-Xxj
	 */
	@Override
	public List<SysDictionaryForPageField> queryFieldAttributesList(Map<String, Object> params) {
    	params.put("loginUser", ShiroUtils.getMandatorId()); //当前登录用户
    	Boolean Stringent = true; //是否严格区分字段大小写
    	if (params.get("Stringent") != null){
    		Stringent = (Boolean) params.get("Stringent");
    	}
    	if (params.get("matchUserDefined") == null || params.get("matchUserDefined") == ""){
        	params.put("matchUserDefined", 1); //1：结果受用户自定义字段属性影响[默认]，0：结果忽略用户自定义字段属性
    	}
    	if (params.get("getFieldAttributesType") == null || params.get("getFieldAttributesType") == ""){
        	params.put("getFieldAttributesType", "page"); //page：全部字段[默认]，pagecallin：调入页网格，pageinhead：头部字段，pageinbottom：底部字段，pagenotingrid：非网格字段，pageingrid：网格字段，pagestatic：静态字段
    	}
    	if (params.get("getFieldAttributesSystemType") == null || params.get("getFieldAttributesSystemType") == ""){
        	params.put("getFieldAttributesSystemType", "web"); //web：网页端；mobile：手机端
    	}
    	List<SysDictionaryForPageField> dictionaryForPageFieldList = dictionaryForFieldMapper.findFieldAttributes(params);
		if (Stringent && params.get("entity") != null && params.get("entity") != ""){
			Map<String, Object> entityFieldMap = TypeUtils.entityFieldsToMap(params.get("entity"));
			for (SysDictionaryForPageField dictionaryForPageField : dictionaryForPageFieldList){
                if (dictionaryForPageField.getFields() != null && entityFieldMap.get(dictionaryForPageField.getFields().toLowerCase()) != null && !"".equals(entityFieldMap.get(dictionaryForPageField.getFields().toLowerCase()))){
                	dictionaryForPageField.setFields(entityFieldMap.get(dictionaryForPageField.getFields().toLowerCase()).toString());
                }
                if (dictionaryForPageField.getFieldMatched() != null && entityFieldMap.get(dictionaryForPageField.getFieldMatched().toLowerCase()) != null && !"".equals(entityFieldMap.get(dictionaryForPageField.getFieldMatched().toLowerCase()))){
                	dictionaryForPageField.setFieldMatched(entityFieldMap.get(dictionaryForPageField.getFieldMatched().toLowerCase()).toString());
                }
			}
		}
    	return dictionaryForPageFieldList;
	}

	/**
	 * 获取功能页面中字段及各属性(以Map形式返回)
	 * @param moduleTable 必要参数：功能唯一标识
     * @param entity 必要参数：用于获取实体属性名取代对应字典字段名，解决大小写敏感问题
	 * @param matchUserDefined 可选参数：是否使用用户自定义字段属性（1：结果受用户自定义字段属性影响[默认]，0：结果忽略用户自定义字段属性）
	 * @param getFieldAttributesType 可选参数：查询范围（page：全部字段[默认]，pagecallin：调入页网格，pageinhead：头部字段，pageinbottom：底部字段，pagenotingrid：非网格字段，pageingrid：网格字段），pagestatic：静态字段
	 * @param getFieldAttributesSystemType 可选参数：类型【web：网页端；mobile：手机端】
	 * @return Map
	 * @author DH-Xxj
	 */
	@Override
	public Map<String, Object> queryFieldAttributesMap(Map<String, Object> params){
    	params.put("loginUser", ShiroUtils.getMandatorId()); //当前用户
    	Boolean Stringent = true; //是否严格区分字段大小写
    	if (params.get("Stringent") != null && params.get("Stringent") != ""){
    		Stringent = false;
    	}
    	if (params.get("matchUserDefined") == null || params.get("matchUserDefined") == ""){
        	params.put("matchUserDefined", 1); //1：结果受用户自定义字段属性影响[默认]，0：结果忽略用户自定义字段属性
    	}
    	if (params.get("getFieldAttributesType") == null || params.get("getFieldAttributesType") == ""){
        	params.put("getFieldAttributesType", "page"); //page：全部字段[默认]，pagecallin：调入页网格，pageinhead：头部字段，pageinbottom：底部字段，pagenotingrid：非网格字段，pageingrid：网格字段，pagestatic：静态字段
    	}
    	if (params.get("getFieldAttributesSystemType") == null || params.get("getFieldAttributesSystemType") == ""){
        	params.put("getFieldAttributesSystemType", "web"); //web：网页端；mobile：手机端
    	}
		List<SysDictionaryForPageField> dictionaryForPageFieldList = dictionaryForFieldMapper.findFieldAttributes(params);
		Map<String, Object> dictionaryForFieldMap = new HashMap<String, Object>();
		if (Stringent && params.get("entity") != null && params.get("entity") != ""){
			Map<String, Object> entityFieldMap = TypeUtils.entityFieldsToMap(params.get("entity"));
			for (SysDictionaryForPageField dictionaryForPageField : dictionaryForPageFieldList) {
	            if (entityFieldMap.get(dictionaryForPageField.getFields().toLowerCase()) != null && !"".equals(entityFieldMap.get(dictionaryForPageField.getFields().toLowerCase()))){
	            	dictionaryForPageField.setFields(entityFieldMap.get(dictionaryForPageField.getFields().toLowerCase()).toString());
	            }
				dictionaryForFieldMap.put(dictionaryForPageField.getFields().toLowerCase(), TypeUtils.entityToMap(dictionaryForPageField));
			} 
		}else{
			for (SysDictionaryForPageField dictionaryForPageField : dictionaryForPageFieldList) {
				dictionaryForFieldMap.put(dictionaryForPageField.getFields().toLowerCase(), TypeUtils.entityToMap(dictionaryForPageField));
			 } 
		}
		return dictionaryForFieldMap;		
	}

	/**
	 * 获取作为查询条件的字段
	 * @param moduleTable 必要参数：功能唯一标识
	 * @return List-SysFieldForConditions
	 * @author DH-Xxj
	 */
	@Override
	public List<SysFieldForConditions> queryFieldFrontConditions(Map<String, Object> params) {
		params.put("getFieldAttributesType", "wherestr");
		return dictionaryForFieldMapper.findFieldFrontConditions(params);
	}
	
	/**
	 * 获取作为导入模板的字段
	 * @param moduleTable 必要参数：功能唯一标识
     * @param entity 必要参数：用于获取实体属性名取代对应字典字段名，解决大小写敏感问题
	 * @return List-Object(json格式数组)
	 * @author DH-Xxj
	 */
	@Override
	public Object queryFieldFrontImport(Map<String, Object> params) {
		Map<String, Object> importFieldsMap = new LinkedHashMap<String, Object>();
		List<SysFieldForConditions> importFieldsList =  dictionaryForFieldMapper.findFieldFrontImport(params);
		if (params.get("entity") != null && params.get("entity") != ""){
			Map<String, Object> entityFieldMap = TypeUtils.entityFieldsToMap(params.get("entity"));
			for (SysFieldForConditions importFields : importFieldsList){
	            if (entityFieldMap.get(importFields.getFields().toLowerCase()) != null && !"".equals(entityFieldMap.get(importFields.getFields().toLowerCase()))){
	            	importFields.setFields(entityFieldMap.get(importFields.getFields().toLowerCase()).toString());
	            }
				importFieldsMap.put(importFields.getFieldName(), importFields.getFields().toString());
			}			
		}else{
			for (SysFieldForConditions importFields : importFieldsList){
				importFieldsMap.put(importFields.getFieldName(), importFields.getFields().toString());
			}			
		}
		return TypeUtils.mapToJson(importFieldsMap);
	}
	
	/**
	 * 获取查询条件SQL语句
	 * @param moduleTable 必要参数：功能唯一标识
	 * @param tablealias 可选参数：查询条件作用表别名，调用方法时传入，可缺省
	 * @param nowherestr 可选参数：若存在（任意值），表示不进行条件过滤
	 * @return String
	 * @author DH-Xxj
	 * @throws Exception 
	 */
	@Override
	public String getWhereStr(Map<String, Object> params) throws Exception{
		String wherestr = "";			//返回的查询字符串
		String fields = "";				//查询字段
		String cFields = "";			//优先查询字段（可自带表别名）
		String tablealias = "";			//表别名
		String sysConditionsType = "";	//系统全局查询类型
		String conditionsType = "";		//查询类型
		String relationWhereStr = "";	//调入关系限制条件

		String wherekeys = "";			//查询条件值
		String whereSubstr = "";		//查询条件子字符串
		
		if (ShiroUtils.getSystemSet() == null){//当session中配置对象为空时，这边去取一次
			SysSetting systemSet = settingService.querySetting();
			sysConditionsType = systemSet.getConditionsType().toString().toLowerCase();
		}else if (ShiroUtils.getSystemSet().getConditionsType() != null && !"".equals(ShiroUtils.getSystemSet().getConditionsType())){
			sysConditionsType = ShiroUtils.getSystemSet().getConditionsType().toString().toLowerCase();
		}else{
			sysConditionsType = "t_equal";
		}
		if (params.get("tablealias") != null && params.get("tablealias") != ""){
			tablealias = params.get("tablealias") + ".";
		}
		if (params.get("relationguid") != null && params.get("relationguid") != ""){
			//如果是调入数据，则查询出调入关系中的调入关系限制条件，并添加到最终查询条件中
			String relationguid = params.get("relationguid").toString();
			SysDictionaryRelationForModule relationForModule = dictionaryRelationForModuleService.queryDictionaryRelationForModuleByGuid(relationguid);
			if (relationForModule != null && relationForModule.getRelationWhereStr() != null){
				relationWhereStr = relationForModule.getRelationWhereStr();
			}
		}else if (params.get("moduleTable") != null && params.get("moduleTable") != ""){
			//如果是常规功能查询，则查询出功能的默认查询条件，并添加到最终查询条件中
    		if(params.get("trueTable") != null && params.get("trueTable") != "") params.put("moduleTable","TS_DictionaryForField");//功能配置时设置moduleTable为TS_DictionaryForField
			String moduleTable = params.get("moduleTable").toString();
			SysDictionaryForModule dictionaryForModule = dictionaryForModuleMapper.findDictionaryForModuleByModuleTable(moduleTable);
			if (dictionaryForModule != null && dictionaryForModule.getModuleWhereStr() != null){
				relationWhereStr = dictionaryForModule.getModuleWhereStr();
			}
		}
		if (relationWhereStr != null && !"".equals(relationWhereStr)){
			wherestr =  "(" + relationWhereStr + ")";
		}

		if (params.get("nowherestr") == null){	//若存在键"nowherestr"（任意值），表示不进行条件过滤
	    	if (params.get("moduleTable") == null || params.get("moduleTable") == ""){
	    		throw new RuntimeException("请提供必要的参数[功能唯一标识]：moduleTable"); 
	    	}else{
	    		if(params.get("trueTable") != null && params.get("trueTable") != "") params.put("moduleTable","TS_DictionaryForField");//功能配置时设置moduleTable为TS_DictionaryForField
	    		List<SysFieldForConditions> fieldForConditionsList = this.queryFieldFrontConditions(params);
				
				for (SysFieldForConditions fieldForConditions : fieldForConditionsList){	//循环数据字典中的查询条件字段
					fields = fieldForConditions.getFields();
					cFields = fieldForConditions.getFieldFrontConditionsField();
					conditionsType = fieldForConditions.getFieldFrontConditionsType().toLowerCase();
					if (!"t_checkcondition".equals(conditionsType) && !"t_in".equals(conditionsType) && (cFields == null || "".equals(cFields))){	
						//未设置优先查询字段时，使用原查询字段，钩选/包含查询条件除外
						cFields = tablealias + fields;
					}
					if (conditionsType == null || "".equals(conditionsType)){	//未设置查询类型时，默认为'相等'类型
						conditionsType = "t_equal";
					}else if ("t_system".equals(conditionsType)){
						conditionsType = sysConditionsType;
					}
					//开始组装查询语句
					if ("t_between".equals(conditionsType)){
						//区间查询
						String sFields = fields + "_s";	//查询区间开始条件参数
						String eFields = fields + "_e";	//查询区间结束条件参数
						for(String keys:params.keySet()){
							if (sFields.toLowerCase().equals(keys.toLowerCase()) && !"".equals(params.get(keys)) ){
								if ("t_date".equals(fieldForConditions.getFieldFrontType().toLowerCase()) || 
										("t_datetime".equals(fieldForConditions.getFieldFrontType().toLowerCase()) && params.get(keys).toString().equals(params.get(keys).toString().substring(0, 10) + " 00:00:00"))
								){
									if ("".equals(wherestr)){
										wherestr =  "(CONVERT(varchar(10)," + cFields + ",23) >= '" + params.get(keys).toString().replace(" 00:00:00", "") + "')";	
									}else{
										wherestr = wherestr + " and (CONVERT(varchar(10)," + cFields + ",23) >= '" + params.get(keys).toString().replace(" 00:00:00", "") + "')";	
									}
								}else{
									if ("".equals(wherestr)){
										wherestr =  "(" + cFields + " >= '" + params.get(keys) + "')";	
									}else{
										wherestr = wherestr + " and (" + cFields + " >= '" + params.get(keys) + "')";	
									}
								}
							}
							if (eFields.toLowerCase().equals(keys.toLowerCase()) && !"".equals(params.get(keys)) ){
								if ("t_date".equals(fieldForConditions.getFieldFrontType().toLowerCase()) || 
										("t_datetime".equals(fieldForConditions.getFieldFrontType().toLowerCase()) && params.get(keys).toString().equals(params.get(keys).toString().substring(0, 10) + " 00:00:00"))
								){
									if ("".equals(wherestr)){
										wherestr =  "(CONVERT(varchar(10)," + cFields + ",23) <= '" + params.get(keys).toString().replace(" 00:00:00", "") + "')";	
									}else{
										wherestr = wherestr + " and (CONVERT(varchar(10)," + cFields + ",23) <= '" + params.get(keys).toString().replace(" 00:00:00", "") + "')";	
									}
								}else{
									if ("".equals(wherestr)){
										wherestr =  "(" + cFields + " <= '" + params.get(keys) + "')";	
									}else{
										wherestr = wherestr + " and (" + cFields + " <= '" + params.get(keys) + "')";	
									}
								}
							}
						}
					}else{
			    		if(params.get("trueTable") != null && params.get("trueTable") != "") params.put("moduleTable","");//功能配置时清空moduleTable
						for(String keys:params.keySet()){
							if (fields.toLowerCase().equals(keys.toLowerCase()) && !"".equals(params.get(keys)) ){
								if ("t_ignore".equals(conditionsType)){
									//忽略组装的条件，做为查询条件显示在页面，但不在此处组装，通常为直接传值到查询语句，以便特殊处理
								}else if ("t_checkcondition".equals(conditionsType)){
									//钩选查询条件
									if (cFields != null && !"".equals(cFields) && "1".equals(params.get(keys).toString())){
										if ("".equals(wherestr)){
											wherestr =  "(" + cFields + ")";
										}else{
											wherestr = wherestr + " and (" + cFields + ")";	
										}
									}
								}else if ("t_in".equals(conditionsType)){
									//包含查询
									if (cFields != null && !"".equals(cFields)){
										wherekeys = params.get(keys).toString();
										whereSubstr = this.getWhereSubStr(sysConditionsType, fields, wherekeys);
										whereSubstr = cFields.replace("@WhereString", "where " + whereSubstr);

										if (!"".equals(whereSubstr)){
											if ("".equals(wherestr)){
												wherestr = whereSubstr;
											}else{
												wherestr = wherestr + " and " + whereSubstr;
											}
										}
									}
									
								}else{ //左右模糊查询、左模糊查询、右模糊查询、相等查询
									wherekeys = params.get(keys).toString();
									whereSubstr = this.getWhereSubStr(conditionsType, cFields, wherekeys);

									if (!"".equals(whereSubstr)){
										if ("".equals(wherestr)){
											wherestr = whereSubstr;
										}else{
											wherestr = wherestr + " and " + whereSubstr;
										}
									}
								}
							}
						}
						
					}
				}	
	    	}
		}		
		return wherestr;
	}
	
	/**
	 * 返回查询条件子字符串
	 * @param conditionsType
	 * @param cFields
	 * @param wherekeys
	 * @return whereSubstr
	 * @author DH-Xxj
	 */
	private String getWhereSubStr(String conditionsType, String cFields, String wherekeys){
		String whereSubstr = "";
		String wherekeyarr[] = null;
		wherekeyarr = wherekeys.split("@@");
		if ("t_bothlike".equals(conditionsType)){ //左右模糊查询
			for (String wherekey : wherekeyarr){
				if (wherekey != null && !"".equals(wherekey)){
					if ("".equals(whereSubstr)){
						whereSubstr = cFields + " like '%" + wherekey + "%'";
					}else{
						whereSubstr = whereSubstr + " or " +cFields + " like '%" + wherekey + "%'";
					}
				}
			}
		}else if ("t_leftlike".equals(conditionsType)){ //左模糊查询
			for (String wherekey : wherekeyarr){
				if (wherekey != null && !"".equals(wherekey)){
					if ("".equals(whereSubstr)){
						whereSubstr = cFields + " like '%" + wherekey + "'";
					}else{
						whereSubstr = whereSubstr + " or " +cFields + " like '%" + wherekey + "'";
					}
				}
			}
		}else if ("t_rightlike".equals(conditionsType)){ //右模糊查询
			for (String wherekey : wherekeyarr){
				if (wherekey != null && !"".equals(wherekey)){
					if ("".equals(whereSubstr)){
						whereSubstr = cFields + " like '" + wherekey + "%'";
					}else{
						whereSubstr = whereSubstr + " or " +cFields + " like '" + wherekey + "%'";
					}
				}
			}
		}else if ("t_unequal".equals(conditionsType)){ //不等
			for (String wherekey : wherekeyarr){
				if (wherekey != null && !"".equals(wherekey)){
					if ("".equals(whereSubstr)){
						whereSubstr = cFields + " != '" + wherekey + "%'";
					}else{
						whereSubstr = whereSubstr + " or " +cFields + " = '" + wherekey + "'";
					}
				}
			}
		}else if ("t_greater".equals(conditionsType)){ //大于
			for (String wherekey : wherekeyarr){
				if (wherekey != null && !"".equals(wherekey)){
					if ("".equals(whereSubstr)){
						whereSubstr = cFields + " > " + wherekey;
					}else{
						whereSubstr = whereSubstr + " or " +cFields + " = '" + wherekey + "'";
					}
				}
			}
		}else if ("t_ungreater".equals(conditionsType)){ //不大于 小于等于
			for (String wherekey : wherekeyarr){
				if (wherekey != null && !"".equals(wherekey)){
					if ("".equals(whereSubstr)){
						whereSubstr = cFields + " <= " + wherekey;
					}else{
						whereSubstr = whereSubstr + " or " +cFields + " = '" + wherekey + "'";
					}
				}
			}
		}else if ("t_smaller".equals(conditionsType)){ //小于
			for (String wherekey : wherekeyarr){
				if (wherekey != null && !"".equals(wherekey)){
					if ("".equals(whereSubstr)){
						whereSubstr = cFields + " < " + wherekey;
					}else{
						whereSubstr = whereSubstr + " or " +cFields + " = '" + wherekey + "'";
					}
				}
			}
		}else if ("t_unsmaller".equals(conditionsType)){ //不小于 大于等于
			for (String wherekey : wherekeyarr){
				if (wherekey != null && !"".equals(wherekey)){
					if ("".equals(whereSubstr)){
						whereSubstr = cFields + " >= " + wherekey;
					}else{
						whereSubstr = whereSubstr + " or " +cFields + " = '" + wherekey + "'";
					}
				}
			}
		}else{ //相等查询
			for (String wherekey : wherekeyarr){
				if (wherekey != null && !"".equals(wherekey)){
					if ("".equals(whereSubstr)){
						whereSubstr = cFields + " = '" + wherekey + "'";
					}else{
						whereSubstr = whereSubstr + " or " +cFields + " = '" + wherekey + "'";
					}
				}
			}
		}
		
		if (!"".equals(whereSubstr)){
			whereSubstr = "(" + whereSubstr + ")";
		}
		return whereSubstr;
	}

	/**
	 * 获取存储过程参数字符串
	 * @param params
	 * @return String
	 * @author DH-Xxj
	 */
	@Override
	public String getProcedureParams(Map<String, Object> params){
		String procedureParams = "";
		String fields = "";				//查询字段
		String cFields = "";			//优先查询字段（可自带表别名）
		String conditionsType = "";		//查询类型
    	if (params.get("moduleTable") == null || params.get("moduleTable") == ""){
    		throw new RuntimeException("请提供必要的参数[功能唯一标识]：moduleTable"); 
    	}else{
    		List<SysFieldForConditions> fieldForConditionsList = this.queryFieldFrontConditions(params);
			
			for (SysFieldForConditions fieldForConditions : fieldForConditionsList){	//循环数据字典中的查询条件字段
				fields = fieldForConditions.getFields();
				cFields = fieldForConditions.getFieldFrontConditionsField();
				conditionsType = fieldForConditions.getFieldFrontConditionsType().toLowerCase();
				if ("t_ignore".equals(conditionsType)){	
					if (cFields == null || "".equalsIgnoreCase(cFields)){
						cFields = fields;
					}
					if (cFields != null && !"".equals(cFields) && fields != null && !"".equals(fields)){
						for(String keys:params.keySet()){
							if (fields.toLowerCase().equals(keys.toLowerCase()) && !"".equals(params.get(keys)) ){
								if ("".equals(procedureParams)){
									procedureParams = "@" + cFields + " = '" + params.get(keys) + "'";
								}else{
									procedureParams = procedureParams + ", @" + cFields + " = '" + params.get(keys) + "'";
								}
							}
						}
					}
				}
			}
    	}
		
		return procedureParams;
	}

	/**
	 * 获取数据权限查询条件SQL语句
	 * @param moduleTable 必要参数：功能唯一标识
	 * @param tablealias 可选参数：查询条件作用表别名，调用方法时传入，可缺省
	 * @param nodatascode 可选参数：若存在（任意值），表示不进行数据权限控制
	 * @return String
	 * @author DH-Xxj
	 * @throws Exception 
	 */
	@Override
	public String getDataScode(Map<String, Object> params) throws Exception{
		String datascode = "";

		if (params.get("nodatascode") == null){	//若存在键"nodatascode"（任意值），表示不进行数据权限控制
	    	if (params.get("moduleTable") == null || params.get("moduleTable") == ""){
	    		throw new RuntimeException("请提供必要的参数[功能唯一标识]：moduleTable"); 
	    	}else{
    			SysUserProcessInstanceTask userProcessInstanceTask = new SysUserProcessInstanceTask();
    			String Processdatascode = "";
        		if (params.get("nid") != null){ //添加流程任务审批（功能任务、通知）数据权限，只要有任务或审批记录的用户就能查看（仅限通过nid查询时生效）
        			String privateNid;
        			if ("".equals(params.get("nid")) || "0".equals(params.get("nid"))){
        				privateNid = "9999999999999999999999";
        			}else{
        				privateNid = params.get("nid").toString();
        			}
        			params.put("privateNid", privateNid);
        			params.put("privatePGuid", privateNid);
        			params.put("privateAUser", ShiroUtils.getMandatorId());

        			if (params.get("flowtype") == null || params.get("flowtype") == ""){  //当前流程任务nid记录
//        				userProcessInstanceTask = dictionaryForFieldMapper.findUserProcessInstanceTaskByNid(params);
        				params.put("params", "this");
        				userProcessInstanceTask = dictionaryForFieldMapper.findUserProcessInstanceTask(params);
        			}else if ("last".equals(params.get("flowtype"))){  //前一流程任务nid记录
//        				userProcessInstanceTask = dictionaryForFieldMapper.findUserProcessInstanceTaskLastNid(params);
        				userProcessInstanceTask = dictionaryForFieldMapper.findUserProcessInstanceTask(params);
        			}else if ("next".equals(params.get("flowtype"))){  //后一流程任务nid记录
//        				userProcessInstanceTask = dictionaryForFieldMapper.findUserProcessInstanceTaskNextNid(params);
        				userProcessInstanceTask = dictionaryForFieldMapper.findUserProcessInstanceTask(params);
        			}else if ("moduletask".equals(params.get("flowtype"))){  //指定nid功能任务记录
        				userProcessInstanceTask = dictionaryForFieldMapper.findUserModuleTaskByPGuid(params);
        			}else if ("modulenotice".equals(params.get("flowtype"))){  //指定nid通知记录
        				userProcessInstanceTask = dictionaryForFieldMapper.findUserModuleNoticeByPGuid(params);
        			}
        			if (userProcessInstanceTask != null && userProcessInstanceTask.getNid() != null){
        				String tablealias = "";
        				if (params.get("tablealias") != null && params.get("tablealias") != ""){
        					tablealias = params.get("tablealias").toString();
        				}
        				if ("".equals(tablealias)){
            				Processdatascode = "nid = '" + userProcessInstanceTask.getNid() + "'";
        				}else{
            				Processdatascode = tablealias + "." + "nid = '" + userProcessInstanceTask.getNid() + "'";
        				}
        			}
        		}else if (params.get("guid") != null){
        			params.put("privatePGuid", params.get("guid").toString());
        			params.put("privateAUser", ShiroUtils.getMandatorId());
        			if ("moduletask".equals(params.get("flowtype"))){  //指定guid功能任务记录
        				userProcessInstanceTask = dictionaryForFieldMapper.findUserModuleTaskByPGuid(params);
        			}else if ("modulenotice".equals(params.get("flowtype"))){  //指定guid通知记录
        				userProcessInstanceTask = dictionaryForFieldMapper.findUserModuleNoticeByPGuid(params);
        			}
        			if (userProcessInstanceTask != null && userProcessInstanceTask.getNid() != null){
        				String tablealias = "";
        				if (params.get("tablealias") != null && params.get("tablealias") != ""){
        					tablealias = params.get("tablealias").toString();
        				}
        				if ("".equals(tablealias)){
            				Processdatascode = "guid = '" + userProcessInstanceTask.getNid() + "'";
        				}else{
            				Processdatascode = tablealias + "." + "guid = '" + userProcessInstanceTask.getNid() + "'";
        				}
        			}
        		}
        		
        		//添加常规数据权限
        		params.put("loginUser", ShiroUtils.getMandatorId());
        		datascode = dictionaryForFieldMapper.findJurisdictionForData(params);
        		
    			if(datascode != null && !"".equals(datascode) && Processdatascode != null && !"".equals(Processdatascode)){
    				datascode = "(" + datascode + " or (" + Processdatascode +"))";
    			}

	    	}
		}
		return datascode;
	}

	/**
	 * 新增功能字段数据字典
	 * @param dictionaryForFieldItems
	 * @return MessageModel
	 * @author lwl
	 */
	@Override
	public AjaxResult insertDictionaryForField(Map<String, Object> params) {
		//return dictionaryForFieldMapper.insert(params);
		List<SysDictionaryForField> dictList = JSON.parseArray(params.get("dictionaryForFieldItems").toString(), SysDictionaryForField.class);
        if (dictList == null || dictList.size() == 0) {
            return AjaxResult.error("数据包格式有误，请检查！");
        }
        for (SysDictionaryForField dictionaryForField : dictList) {
            
        	dictionaryForFieldMapper.insertDictionaryForField(dictionaryForField);
        }
        return AjaxResult.success("操作成功");
	}

	/**
	 * 修改功能字段数据字典
	 * @param dictionaryForFieldItems
	 * @return MessageModel
	 * @author DH-Xxj
	 */
	@Override
	public AjaxResult updateDictionaryForField(Map<String, Object> params) {
		if (StringUtils.isEmpty(params)) {
			return AjaxResult.error("数据提交失败，必填参数有误！");
		}
		List<SysDictionaryForField> dictList = JSON.parseArray(params.get("dictionaryForFieldItems").toString(), SysDictionaryForField.class);
		if (dictList == null || dictList.size() == 0) {
            return AjaxResult.error("数据包格式有误，请检查！");
        }
		for (SysDictionaryForField dictionaryForField : dictList) {
			dictionaryForFieldMapper.updateDictionaryForField(dictionaryForField);
		}
		return AjaxResult.success("操作成功！");
	}

	/**
	 * 删除功能字段数据字典
	 * @param dictionaryForFieldItems
	 * @return MessageModel
	 * @author lwl
	 */
	@Override
	public AjaxResult deleteDictionaryForField(Map<String, Object> params) {
		List<SysDictionaryForField> dictList = JSON.parseArray(params.get("dictionaryForFieldItems").toString(), SysDictionaryForField.class);
		if (dictList == null || dictList.size() == 0) {
			return AjaxResult.error("数据包格式有误，请检查！");
		}
		for (SysDictionaryForField dictionaryForField : dictList) {
			dictionaryForFieldMapper.deleteDictionaryForFieldByGuid(dictionaryForField);
		}
		return AjaxResult.success("操作成功");
	}
	
	@Override
	public List<SysDictionaryForField> getDictionaryForFieldModuleTableData(String moduleTable) {
		return dictionaryForFieldMapper.getDictionaryForFieldModuleTableData(moduleTable);
	}

	/**
	 * 同步列名
	 * @param moduleTable
	 */
	@Override
	public AjaxResult tblm(String moduleTable) {
		//根据数据库获取字段名称
		List<Map<String, Object>> moduleTableNameList = dictionaryForFieldMapper.searchPC(moduleTable);
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("moduleTable",moduleTable);
		try {
			List<SysDictionaryForField> sysDictionaryForFields = dictionaryForFieldMapper.findDictionaryForFieldByTableName(params);
			for (SysDictionaryForField sysDictionaryForField : sysDictionaryForFields){
				for (Map<String, Object> moduleTableName :moduleTableNameList){
					if (moduleTableName.get("name").equals(sysDictionaryForField.getFields())){
						sysDictionaryForField.setFieldAlias(String.valueOf(moduleTableName.get("value")));
						sysDictionaryForField.setFieldName(String.valueOf(moduleTableName.get("value")));
						dictionaryForFieldMapper.updateDictionaryForField(sysDictionaryForField);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return AjaxResult.success("操作成功");
	}
}
